package com.xiaoa.gossip.cluster.init;

import com.xiaoa.gossip.cluster.command.CurrentNodeState;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Date;

import static com.xiaoa.gossip.cluster.command.NodeState.NODE_STATE_START;

/**
 * 节点初始化
 *
 * @author luokaichuang
 * @time 2020/5/7
 */

@Component
public class NoteInit {

    @Value("${server.port}")
    private int port;

    @Value("${spring.application.name}")
    private String name;

    @Bean
    public CurrentNodeState currentNodeState() throws Exception {

        CurrentNodeState nodeState = new CurrentNodeState();
        nodeState.setId(String.valueOf(System.nanoTime()));
        nodeState.setPort(port);
        nodeState.setIp(getLocalIp());
        nodeState.setState(NODE_STATE_START);
        nodeState.setName(name);
        nodeState.setStartTime(new Date());
        nodeState.setDataVersion(1L);
        return nodeState;
    }

    /**
     * 获取当前机器ip
     **/
    private String getLocalIp() throws Exception {
        InetAddress address = InetAddress.getLocalHost();
        return address.getHostAddress();
    }

}
